import requests
from bs4 import BeautifulSoup
import time

# 设置请求头，模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}


def get_dropdown_options(url):
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

    dropdown = soup.find('select')  # 根据实际情况修改标签和属性
    if not dropdown:
        print("未找到下拉菜单")
        return []

    options = dropdown.find_all('option')
    return [option['value'] for option in options if option.get('value')]


def get_video_url(video_page_url):
    response = requests.get(video_page_url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

    # 根据实际情况修改视频链接的提取方式
    video_tag = soup.find('video')
    if video_tag and video_tag.get('src'):
        return video_tag['src']
    else:
        print("未找到视频链接")
        return None


def download_video(video_url, save_path):
    response = requests.get(video_url, headers=headers, stream=True)
    with open(save_path, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            if chunk:
                f.write(chunk)
    print(f"视频已下载到 {save_path}")


def main():
    base_url = 'https://www.mingrisoft.com/bookvideo/9374.html'  # 替换为目标网站URL
    dropdown_options = get_dropdown_options(base_url)

    if not dropdown_options:
        return

    for index, option in enumerate(dropdown_options, start=1):
        video_page_url = f"{base_url}?option={option}"  # 根据实际情况构建视频页面URL
        print(f"正在处理第 {index} 个选项: {option}")

        video_url = get_video_url(video_page_url)
        if not video_url:
            continue

        save_path = f"video_{index}.mp4"
        download_video(video_url, save_path)

        time.sleep(1)  # 避免过于频繁的请求


if __name__ == '__main__':
    main()